/**
 * 导航管理器
 * 负责处理导航状态和页面加载
 */
class Navigation {
  constructor() {
    // 初始化状态
    this.currentPage = this._getCurrentPage();
    this.mobileMenuOpen = false;
    this.isLoading = false;
    this.mainContentElement = document.getElementById('dynamic-content');
    this.loadingIndicator = document.getElementById('loading-indicator');
    
    // 绑定方法到实例
    this.loadPage = this.loadPage.bind(this);
    this.handlePopState = this.handlePopState.bind(this);
    
    // 初始化事件监听
    window.addEventListener('popstate', this.handlePopState);
  }

  /**
   * 获取当前页面路径
   * @returns {string} 当前页面路径
   * @private
   */
  _getCurrentPage() {
    const urlParams = new URLSearchParams(window.location.search);
    const page = urlParams.get('p') || 'dashboard';
    return `index.html?p=${page}`;
  }

  /**
   * 显示加载指示器
   * @private
   */
  _showLoading() {
    if (this.loadingIndicator) {
      this.loadingIndicator.classList.remove('hidden');
    }
    if (this.mainContentElement) {
      this.mainContentElement.classList.add('loading');
    }
  }

  /**
   * 隐藏加载指示器
   * @private
   */
  _hideLoading() {
    if (this.loadingIndicator) {
      this.loadingIndicator.classList.add('hidden');
    }
    if (this.mainContentElement) {
      this.mainContentElement.classList.remove('loading');
    }
  }

  /**
   * 更新页面标题
   * @param {string} href - 页面路径
   * @private
   */
  _updatePageTitle(href) {
    const titleElement = document.querySelector(`[data-page="${href}"]`);
    if (titleElement) {
      document.title = titleElement.getAttribute('data-title') || '智能投资助手';
    }
  }

  /**
   * 触发页面变化事件
   * @param {string} href - 页面路径
   * @private
   */
  _emitPageChangeEvent(href) {
    document.dispatchEvent(new CustomEvent('navigation:pageChanged', {
      detail: { currentPage: href }
    }));
  }

  /**
   * 处理页面加载错误
   * @param {Error} error - 错误对象
   * @private
   */
  _handleError(error) {
    console.error('页面加载错误:', error);
    if (this.mainContentElement) {
      this.mainContentElement.innerHTML = `
        <div class="flex flex-col items-center justify-center py-12">
          <svg class="w-16 h-16 text-gray-400" fill="none" viewBox="0 0 24 24" stroke="currentColor">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z"/>
          </svg>
          <h2 class="mt-4 text-xl font-semibold text-gray-900 dark:text-gray-100">页面加载失败</h2>
          <p class="mt-2 text-gray-600 dark:text-gray-400">请稍后重试或联系技术支持</p>
          <button onclick="window.navigationInstance.loadPage('${this.currentPage}')" 
                  class="mt-4 px-4 py-2 bg-blue-500 text-white rounded hover:bg-blue-600 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2">
            重试
          </button>
        </div>
      `;
    }
  }

  /**
   * 初始化导航
   */
  init() {
    // 初始化移动菜单状态
    this.initializeMobileMenu();
    
    // 初始化暗色模式
    this.initializeDarkMode();
    
    // 初始化用户菜单
    this.initializeUserMenu();
    
    // 加载初始页面
    const initialPage = this._getCurrentPage();
    this.loadPage(initialPage, true);
    
    // 发布导航就绪事件
    window.dispatchEvent(new CustomEvent('navigation:ready'));
  }

  /**
   * 初始化移动菜单
   */
  initializeMobileMenu() {
    const mobileMenuButton = document.getElementById('mobile-menu-button');
    const mobileMenu = document.getElementById('mobile-menu');
    const menuOpenIcon = document.getElementById('menu-open-icon');
    const menuCloseIcon = document.getElementById('menu-close-icon');

    if (mobileMenuButton && mobileMenu) {
      mobileMenuButton.addEventListener('click', () => {
        this.toggleMobileMenu();
      });
    }
  }

  /**
   * 初始化暗色模式
   */
  initializeDarkMode() {
    const darkMode = localStorage.getItem('darkMode') === 'true';
    const darkModeToggle = document.getElementById('dark-mode-toggle');
    const lightIcon = document.getElementById('light-icon');
    const darkIcon = document.getElementById('dark-icon');

    // 设置初始状态
    if (darkMode) {
      document.documentElement.classList.add('dark');
      if (lightIcon && darkIcon) {
        lightIcon.classList.add('hidden');
        darkIcon.classList.remove('hidden');
      }
    }

    // 绑定切换事件
    if (darkModeToggle) {
      darkModeToggle.addEventListener('click', () => {
        document.documentElement.classList.toggle('dark');
        if (lightIcon && darkIcon) {
          lightIcon.classList.toggle('hidden');
          darkIcon.classList.toggle('hidden');
        }
        localStorage.setItem('darkMode', document.documentElement.classList.contains('dark'));
      });
    }
  }

  /**
   * 初始化用户菜单
   */
  initializeUserMenu() {
    const userMenuButton = document.getElementById('user-menu-button');
    const userMenu = document.getElementById('user-menu');

    if (userMenuButton && userMenu) {
      userMenuButton.addEventListener('click', () => {
        userMenu.classList.toggle('hidden');
      });

      // 点击其他区域关闭菜单
      document.addEventListener('click', (event) => {
        if (!userMenuButton.contains(event.target) && !userMenu.contains(event.target)) {
          userMenu.classList.add('hidden');
        }
      });
    }
  }

  /**
   * 处理浏览器前进/后退
   * @param {PopStateEvent} event - 浏览器历史事件
   */
  handlePopState(event) {
    const currentPage = this._getCurrentPage();
    this.loadPage(currentPage, true);
  }

  /**
   * 加载页面内容
   * @param {string} href - 页面路径
   * @param {boolean} [skipPushState=false] - 是否跳过历史记录
   */
  async loadPage(href, skipPushState = false) {
    // 防止重复加载
    if (this.isLoading) return;
    
    // 立即更新当前页面状态，避免闪烁
    this.currentPage = href;
    this._emitPageChangeEvent(href);
    
    // 解析页面路径
    const url = new URL(href, window.location.href);
    const pageName = url.searchParams.get('p') || 'dashboard';
    const pagePath = `pages/${pageName}.html`;
    
    // 开始加载
    this.isLoading = true;
    this._showLoading();

    try {
      // 获取页面内容
      const response = await fetch(pagePath);
      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
      }
      
      // 更新页面内容
      const content = await response.text();
      if (this.mainContentElement) {
        this.mainContentElement.innerHTML = content;
      }

      // 更新浏览器历史和页面标题
      if (!skipPushState) {
        history.pushState({}, '', url);
      }
      this._updatePageTitle(href);

      // 关闭移动菜单
      if (this.mobileMenuOpen) {
        this.toggleMobileMenu();
      }

      // 触发页面加载完成事件
      window.dispatchEvent(new CustomEvent('page:loaded', { 
        detail: { page: pageName } 
      }));
      
    } catch (error) {
      this._handleError(error);
    } finally {
      this.isLoading = false;
      this._hideLoading();
    }
  }

  /**
   * 切换移动菜单
   */
  toggleMobileMenu() {
    this.mobileMenuOpen = !this.mobileMenuOpen;
    const mobileMenu = document.getElementById('mobile-menu');
    const menuOpenIcon = document.getElementById('menu-open-icon');
    const menuCloseIcon = document.getElementById('menu-close-icon');

    if (mobileMenu) {
      mobileMenu.classList.toggle('hidden', !this.mobileMenuOpen);
    }
    if (menuOpenIcon) {
      menuOpenIcon.classList.toggle('hidden', this.mobileMenuOpen);
    }
    if (menuCloseIcon) {
      menuCloseIcon.classList.toggle('hidden', !this.mobileMenuOpen);
    }
  }
}

// 创建全局导航实例
window.navigationInstance = new Navigation();

// 导出给 Alpine.js 使用的导航函数
window.navigation = function() {
    // 确保只初始化一次
    if (!window.navigationInitialized) {
      window.navigationInitialized = true;
      window.navigationInstance.init();
    }
    
    // 创建响应式状态对象
    const state = {
      currentPage: window.navigationInstance.currentPage,
      mobileMenuOpen: window.navigationInstance.mobileMenuOpen,
      
      loadPage(href) {
        // 立即更新状态，避免闪烁
        this.currentPage = href;
        window.navigationInstance.loadPage(href);
      },
      
      toggleMobileMenu() {
        this.mobileMenuOpen = !this.mobileMenuOpen;
        window.navigationInstance.toggleMobileMenu();
      }
    };

    // 监听页面变化事件
    document.addEventListener('navigation:pageChanged', (event) => {
      state.currentPage = event.detail.currentPage;
    });

    return state;
};